<?php

/**
 * 工具类的相关函数
 */

use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;

if (!function_exists('is_json')) {
    /**
     * 判断是否是json
     *
     * @param string $jsonstr
     * @return array|boolean
     */
    function is_json(string $jsonstr): array|false
    {
        $jsonarr = json_decode($jsonstr, true);
        return (json_last_error() == JSON_ERROR_NONE) ? $jsonarr : false;
    }
}

if (!function_exists('pic_scale')) {
    /**
     * 图片缩放 仅public目录有效
     *
     * @param string $imgpath
     * @param integer $w
     * @param integer $h
     * @return string
     */
    function pic_scale(string $imgpath, int $w, int $h): string
    {
        $pathinfo = pathinfo($imgpath);
        $readpath = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '_' . $w . '_' . $h . '.' . $pathinfo['extension'];
        $savepath = public_path() . $readpath;
        if (file_exists($savepath)) {
            return $readpath;
        }

        if (!file_exists(public_path() . $imgpath)) {
            return '';
        }

        $manager = new ImageManager(new Driver());
        $image = $manager->read(public_path() . $imgpath)->scale($w, $h);

        $image->save($savepath);
        return $readpath;
    }
}

if (!function_exists('pic_crop')) {
    /**
     *  图片裁剪(缩放后裁剪) 仅public目录有效
     *
     * @param string $imgpath
     * @param integer $w
     * @param integer $h
     * @return string
     */
    function pic_crop(string $imgpath, int $w, int $h): string
    {
        if (trim($imgpath) == '' || !file_exists(public_path() . $imgpath)) {
            return $imgpath;
        }
        $pathinfo = pathinfo($imgpath);
        $readpath = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '_' . $w . '_' . $h . '.' . $pathinfo['extension'];
        $savepath = public_path() . $readpath;
        if (file_exists($savepath)) {
            return $readpath;
        }
        if (!file_exists(public_path() . $imgpath)) {
            return '';
        }
        $manager = new ImageManager(new Driver());
        $image = $manager->read(public_path() . $imgpath);
        if ($image->height() > $image->width()) {
            $image->scale(
                height: $h,
            )->crop(
                width: $w,
                height: $h,
                position: 'center'
            );
        } else {
            $image->scale(
                width: $w,
            )->crop(
                width: $w,
                height: $h,
                position: 'center'
            );
        }
        $image->save($savepath);
        return $readpath;
    }
}


if (!function_exists('pic_crop_noscale')) {
    /**
     *  图片裁剪(不缩放成裁剪) 仅public目录有效
     *
     * @param string $imgpath
     * @param integer $w
     * @param integer $h
     * @return string
     */
    function pic_crop_noscale(string $imgpath, int $w, int $h): string
    {
        if (trim($imgpath) == '' || !file_exists(public_path() . $imgpath)) {
            return $imgpath;
        }

        $pathinfo = pathinfo($imgpath);
        $readpath = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '_' . $w . '_' . $h . '.' . $pathinfo['extension'];
        $savepath = public_path() . $readpath;
        if (file_exists($savepath)) {
            return $readpath;
        }
        if (!file_exists(public_path() . $imgpath)) {
            return '';
        }
        $manager = new ImageManager(new Driver());
        $image = $manager->read(public_path() . $imgpath);
        if ($image->height() > $image->width()) {
            $image->crop(
                width: $w,
                height: $h,
                position: 'center'
            );
        } else {
            $image->crop(
                width: $w,
                height: $h,
                position: 'center'
            );
        }
        $image->save($savepath);
        return $readpath;
    }
}


if (!function_exists('format_bytes')) {
    /**
     * 字节转换成合适的单位
     *
     * @param [type] $size
     * @return void
     */
    function format_bytes($size)
    {
        $units = [' B', ' KB', ' MB', ' GB', ' TB'];
        for ($i = 0; $size >= 1024 && $i < 4; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $units[$i];
    }
}


if (!function_exists('flattenArray')) {
    /**
     * 多维数组转一维数组
     *
     * @param array $arr
     * @return array
     */
    function flattenArray(array $arr): array
    {
        $result = array();
        foreach ($arr as $value) {
            if (is_array($value)) {
                $result = array_merge($result, flattenArray($value));
            } else {
                $result[] = $value;
            }
        }
        return $result;
    }
}


if (!function_exists('common_regex')) {
    /**
     * 常用正则表达式
     *
     * @return array
     */
    function common_regex(): array
    {
        return [
            '/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/' => '邮箱',
            '/^\d{1,4}(-)(1[0-2]|0?[1-9])\1(0?[1-9]|[1-2]\d|30|31)$/'                                                                                                 => '日期',
            '/^(?:(?:\+|00)86)?1[3-9]\d{9}$/'                                                                                                                         => '手机',
            '/^\d+$/'                                                                                                                                                 => '数字',
            '/^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/'                                                                                                                      => '金额',
            '/^[A-Z]+$/'                                                                                                                                              => '大小写英文',
            '/^(-?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*|0\.0+)$/'                                                                                                            => '浮点数',
            '/^-[1-9]\d*$/'                                                                                                                                           => '小于0的负整数',
            '/^[A-Za-z0-9]+$/'                                                                                                                                        => '数字和字母',
            '/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/'                                 => '车牌(支持新能源)',
            '/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/'                                                                                                  => '统一社会信用代码',
            '/^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/'                                                        => '网址',
            '/^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/'                                                                           => '邮编',
            '/^(?:0|(?:-?[1-9]\d*))$/'                                                                                                                                => '整数',
            '/^\+?[1-9]\d*$/'                                                                                                                                         => '正整数',
            '/^(?:[\u4e00-\u9fa5·]{2,16})$/'                                                                                                                          => '中文姓名',
        ];
    }
}



if (!function_exists('regroup_url_param')) {
    /**
     * 重组URL GET参数
     *
     * @param array $excludes 排除的GET参数
     * @param array $appends 追加的GET参数
     * @param string $url
     * @return string
     */
    function regroup_url_param(array $excludes = [], array $appends = [], string $url = ''): string
    {

        $gets = request()->get();
        foreach ($excludes as $exclude) {
            if (isset($gets[$exclude])) {
                unset($gets[$exclude]);
            }
        }
        foreach ($appends as $key => $append) {
            $gets[$key] = $append;
        }

        if ($url == '') {
            $url = get_now_url();
        } else {
            $url = explode('?', $url)[0];
        }
        return $url .= '?' . http_build_query($gets);
    }
}

if (!function_exists('ad_ant_shielding')) {
    /**
     * 链接防止被当作广告屏蔽
     *
     * @param string $str
     * @return string
     */
    function ad_ant_shielding(string $str): string
    {
        $anturl    = '/ant_shielding_url/';
        $anturl .= base64_encode($str);
        return $anturl;
    }
}
